<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    label-position="left"
  >
    <el-form-item label="手机号" prop="telephone">
      <el-input v-model="ruleForm.telephone" clearable />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off" clearable />
    </el-form-item>
    <el-form-item>
      <div class="form-button">
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
        <el-button @click="goToSmsForm">短信登录</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { showErrorMsg } from '@/utils/alterMessage.js'
import { useLoginStore } from '@/stores/login/login.js'
import { storeToRefs } from 'pinia'

const ruleFormRef = ref()
const loginStore = useLoginStore()

const { ruleForm } = storeToRefs(loginStore)

const validateTel = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    // 假设有效的手机号为11位数字，且以1开头
    // /^1[3-9]\d{9}$/ /^1\d{10}$/
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入有效的手机号'))
    } else {
      callback()
    }
  }
}

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6'))
  } else {
    callback()
  }
}

const rules = reactive({
  telephone: [{ validator: validateTel, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loginStore.loginByPwd()
    } else {
      showErrorMsg('请输入正确的手机号和密码')
    }
  })
}
const goToSmsForm = () => {
  //跳转至/login/TelAndSms界面用router
  // router.push('/login/TelAndSms')
  // router.replace('/login/TelAndSms')
  window.location.href = '/login/TelAndSms'
}
// const resetForm = (formEl) => {
//   if (!formEl) return
//   formEl.resetFields()
// }
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  .form-button {
    width: 100%;
    height: 100%;
    display: flex;
    margin-top: 20px;
    //均匀
    justify-content: space-between;
  }
}
</style>
